package com.company.project.controller;

import com.auth0.jwt.algorithms.Algorithm;
import com.company.project.annotation.OperLog;
import com.company.project.core.Result;
import com.company.project.core.ResultGenerator;
import com.company.project.dao.SysUserMapper;
import com.company.project.dto.findUserListDto;
import com.company.project.dto.loginReturn;
import com.company.project.model.SysUser;
import com.company.project.service.SysUserService;
import com.company.project.utilClass.RSA;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.security.interfaces.RSAPrivateKey;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.auth0.jwt.JWT;

/**
 * Created by DLHTX on 2020/06/21.
 */
@RestController
@RequestMapping("/api/user")
@Api(tags = "用户控制器")
public class SysUserController {
    @Resource
    private SysUserService sysUserService;
    private RSA RSACoder;

    private static final String TOKEN_SECRET="TOKENSCRET";  //密钥盐
    private static final long EXPIRE_TIME= 15*60*1000;

    @Resource
    private SysUserMapper sysUserMapper;

    @PostMapping("/addUser")
    @OperLog(operModul = "用户管理-用户列表",operType = "添加",operDesc = "添加用户")
    public Result add(@RequestBody SysUser sysUser) throws Exception {
        //数据的加密
        byte[] encryedPass = RSACoder.encryptByPrivateKey(sysUser.getPassword().getBytes(), Base64.decodeBase64(RSA.privatekey));
        sysUser.setPassword(Base64.encodeBase64String(encryedPass));
        sysUserService.save(sysUser);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/editUser")
    @OperLog(operModul = "用户管理-用户列表",operType = "更新",operDesc = "更新用户")
    public Result editUser(@RequestBody SysUser sysUser) throws Exception {
        //数据的加密
        if (sysUser.getPassword() != null & sysUser.getPassword() != "") {
            byte[] encryedPass = RSACoder.encryptByPrivateKey(sysUser.getPassword().getBytes(), Base64.decodeBase64(RSA.privatekey));
            sysUser.setPassword(Base64.encodeBase64String(encryedPass));
        }

        sysUserService.update(sysUser);
        return ResultGenerator.genSuccessResult();
    }

    private static Map<String, Object> transBean2Map(Object obj) {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                // 过滤class属性
                if (!key.equals("class") && !key.equals("pageNo") && !key.equals("pageSize")) {
                    // 得到property对应的getter方法
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(obj);
                    map.put(key, value);
                }
            }
        } catch (Exception e) {
            System.out.println("transBean2Map Error " + e);
        }
        return map;

    }

    @PostMapping("/login")
    public Result login(@RequestBody SysUser sysUser) {
        try {
            List<loginReturn> list = sysUserMapper.findUser(sysUser);
            if(list.size() == 0){
                return ResultGenerator.genFailResult("用户名或密码错误");
            }else{
                Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);

                Map userInfo = transBean2Map(list.get(0));
                String token = "";
                token = JWT.create().withExpiresAt(expiresAt).withAudience(sysUser.getName()).sign(Algorithm.HMAC256(TOKEN_SECRET));
                userInfo.put("token",token);
                return ResultGenerator.genSuccessResult(userInfo);
            }
        } catch (Exception err) {
            return ResultGenerator.genFailResult("用户名或密码错误");
        }
    }

    @PostMapping("/getUserList")
    public Result getUserList(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer row) {
        List<findUserListDto> list = sysUserMapper.findUserList();
        return ResultGenerator.genSuccessResult(list);
    }
}
